<style scoped lang="scss">
@import url('index.scss');
</style>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="5">
        <div class="left_con">
          <div class="toptime">
            <!-- <el-date-picker-panel v-model="indexdate" /> -->
            <el-date-picker-panel type="date" v-model="indexdate" :border="false" @panel-change="handlePanelChange"
              date-format="YYYY-MM-DD" :disabled-date="disabledDate">
              <!-- <template #default="{ date, isSelected }">
                <CalendarCell :date="date" :is-selected="isSelected" :weekend-class="weekendClass(date)" />
              </template> -->
            </el-date-picker-panel>
          </div>
          <div class="searchform">
            <div class="searchform_item">
              <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
                <el-form-item label="姓名" prop="uname">
                  <el-input v-model="queryParams.uname" placeholder="请输入患者姓名" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="身份证号" prop="ucard">
                  <el-input v-model="queryParams.ucard" placeholder="请输入患者身份证号" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="手机号" prop="umobile">
                  <el-input v-model="queryParams.umobile" placeholder="请输入患者手机号" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <!-- <el-form-item label="出生年月" prop="ubirthday">
                  <el-input v-model="queryParams.ubirthday" placeholder="请输入患者出生年月" clearable
                    @keyup.enter="handleQuery" />
                </el-form-item> -->
                <el-form-item label="社保卡号" prop="ssid">
                  <el-input v-model="queryParams.ssid" placeholder="请输入患者社保卡号" clearable @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="预约时间" prop="appointmenttime">
                  <el-date-picker clearable v-model="queryParams.appointmenttime" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择预约时间">
                  </el-date-picker>
                </el-form-item>
                <el-form-item>
                  <el-button class="newButton" icon="Search" @click="handleQuery">查询</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="19">
        <div class="right_top topsearch">
          <el-row>
            <el-col :span="24" class="rightcol">
              <div class="newbtn" @click="handleAdd" v-hasPermi="['system:patient:add']">
                <img src="@/assets/images/add.svg" alt="">
                <span>新增</span>
              </div>
              <div class="newbtn" v-if="single == false" @click="handleUpdate" v-hasPermi="['system:patient:edit']">
                <img src="@/assets/images/edit.svg" alt=""></img>
                <span>编辑</span>
              </div>
              <div class="newbtn" v-if="multiple == false" @click="handleDelete" v-hasPermi="['system:patient:remove']">
                <img src="@/assets/images/del.svg" alt=""></img>
                <span>删除</span>
              </div>
              <div class="newbtn" @click="handleExport" v-hasPermi="['system:patient:export']">
                <img src="@/assets/images/export.svg" alt=""></img>
                <span>导出</span>
              </div>
              <div class="newbtn" @click="getList">
                <img src="@/assets/images/refresh.svg" alt=""></img>
                <span>刷新</span>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="right_bottom newtable">
          <el-table v-loading="loading" :data="patientList" @selection-change="handleSelectionChange"
            :cell-style="{ backgroundColor: '#f9f9f9' }">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="expand" width="55" label="展开">
              <template #default="props">
              <div class="detail">
                <el-row :gutter="20">
                  <el-col :span="8">
                    <p><b>姓名：</b>{{ props.row.uname }}</p>
                  </el-col>
                  <el-col :span="8">
                    <p><b>性别：</b>{{ props.row.usex == 0 ? '男' : (props.row.usex == 1 ? '女' : '未知') }}</p>
                  </el-col>
                  <el-col :span="8">
                    <p><b>年龄：</b>{{ props.row.age }}</p>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <p><b>身份证号：</b>{{ props.row.ucard }}</p>
                  </el-col>
                  <el-col :span="8">
                    <p><b>手机号：</b>{{ props.row.umobile }}</p>
                  </el-col>
                  <el-col :span="8">
                    <p><b>出生年月：</b>{{ props.row.ubirthday }}</p>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <el-col :span="8">
                    <p><b>社保卡号：</b>{{ props.row.ssid }}</p>
                  </el-col>
                  <el-col :span="8">
                    <p><b>婚姻情况：</b>{{ props.row.maritalstatus }}</p>
                  </el-col>
                  <el-col :span="8">
                    <p><b>居住地址：</b>{{ JSON.parse(props.row.addresscity).map(item => item).join('') + props.row.address }}</p>
                  </el-col>
                </el-row>
                <el-row :gutter="20">
                  <!-- <el-col :span="8">
                    <p><b>预约类型：</b>{{ props.row.appointmenttype }}</p>
                  </el-col> -->
                  <el-col :span="8" v-if="props.row.appointmenttime">
                    <p><b>预约时间：</b>{{ parseTime(props.row.appointmenttime, '{y}-{m}-{d}') }}</p>
                  </el-col>
                  <el-col :span="16" v-if="!props.row.appointmentitems">
                    <p><b>预约项目：</b>{{ JSON.parse(props.row.appointmentitems).map(item => checkList.find(listItem => listItem.itemid == item)?.name).join('、') }}</p>
                  </el-col>
                </el-row>
                <!-- <el-row :gutter="20">
                  <el-col :span="24">
                    <p><b>预约项目：</b>{{ JSON.parse(props.row.appointmentitems).map(item => checkList.find(listItem => listItem.itemid == item)?.name).join('、') }}</p>
                  </el-col>
                </el-row> -->
                </div>
              </template>
            </el-table-column>

            <el-table-column label="ID" width="55" align="center" prop="uid" >
            </el-table-column>
            <el-table-column label="姓名" width="85" align="center" prop="uname" />
            <el-table-column label="性别" width="55" align="center" prop="usex" >
              <template #default="scope">
                <span v-if="scope.row.usex == '0'">男</span>
                <span v-else-if="scope.row.usex == '1'">女</span>
                <span v-else>未知</span>
              </template>
            </el-table-column>
            <el-table-column label="年龄" min-width="55" align="center" prop="age" />
            <el-table-column label="婚姻状态" width="85" align="center" prop="wedstatus" >
              <template #default="scope">
               {{ ha_wed_status.find(item => item.value == scope.row.maritalstatus)?.label || '未知' }}
              </template>
            </el-table-column>
            <!-- <el-table-column label="身份证号" width="180" align="center" prop="ucard" /> -->
            <el-table-column label="手机号"  width="130" align="center" prop="umobile" />
            <el-table-column label="出生年月" min-width="130" align="center" prop="ubirthday" />

            <!-- <el-table-column label="社保卡号" width="180"  align="center" prop="ssid" /> -->
            <!-- <el-table-column label="婚姻情况" align="center" prop="maritalstatus" />-->
            <!-- <el-table-column label="居住地址" min-width="180" align="center" prop="address" >
              <template #default="scope">
                <span>{{ JSON.parse(scope.row.addresscity).map(item => item).join('') + scope.row.address }}</span>
              </template>
            </el-table-column> -->
            <!-- <el-table-column label="预约类型" align="center" prop="appointmenttype" /> -->
            <!-- <el-table-column label="预约项目"  align="center" prop="appointmentitems" >
              <template #default="scope">
                <span>{{ JSON.parse(scope.row.appointmentitems).map(item => checkList.find(listItem => listItem.itemid == item)?.name).join('、') }}</span>
              </template>
            </el-table-column> -->
            <el-table-column label="预约时间" align="center" prop="appointmenttime" width="180">
              <template #default="scope">
                <span>{{ parseTime(scope.row.appointmenttime, '{y}-{m}-{d} {h}:{i}') }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column label="发送短信" align="center" prop="sendsms" /> -->
            <el-table-column label="预约状态" align="center" prop="ustatus" >
              <template #default="scope">
                <el-tag v-if="scope.row.ustatus == '0'" type="error">未预约</el-tag>
                <el-tag v-else-if="scope.row.ustatus == '1'" type="success">已预约</el-tag>
                <el-tag v-else type="error">未预约</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="就诊状态" align="center" prop="pstatus" >
              <template #default="scope">
                <el-tag v-if="scope.row.pstatus == '0'" type="error">未就诊</el-tag>
                <el-tag v-else-if="scope.row.pstatus == '1'" type="info">就诊中</el-tag>
                <el-tag v-else-if="scope.row.pstatus == '2'" type="success">已就诊</el-tag>
                <el-tag v-else type="error">未就诊</el-tag>
              </template>
            </el-table-column>
            <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
            <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['system:patient:edit']">修改</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['system:patient:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />
        </div>
      </el-col>
    </el-row>



    <!-- 添加或修改患者管理对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" class="newDialog">
      <el-form ref="patientRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="姓名" prop="uname">
              <el-input v-model="form.uname" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="usex">
              <!-- <el-radio-group v-model="form.usex">
                <el-radio v-for="item in sys_user_sex" :label="item.value" :key="item.value">{{ item.label }}</el-radio>
              </el-radio-group> -->
              <el-select v-model="form.usex" placeholder="请选择性别" clea>
               <el-option v-for="item in sys_user_sex" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="身份证号" prop="ucard">
              <el-input v-model="form.ucard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生年月" prop="ubirthday">
              <!-- <el-input v-model="form.ubirthday" placeholder="请输入患者出生年月" /> -->
              <el-date-picker clearable v-model="form.ubirthday" type="date" value-format="YYYY-MM-DD" disabled
                placeholder="请选择出生年月" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="社保卡号" prop="ssid">
              <el-input v-model="form.ssid" placeholder="请输入社保卡号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="umobile">
              <el-input v-model="form.umobile" placeholder="请输入手机号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="婚姻状态" prop="wedstatus">
              <el-select v-model="form.maritalstatus" placeholder="请选择婚姻状态" clearable>
                <el-option v-for="item in ha_wed_status" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="居住地址" prop="address">
              <el-cascader v-model="form.addresscity" :options="options" clearable filterable style="width: 100%;"
                :props="propsNew">
                <template #default="{ node, data }">
                  <span>{{ data.name }}</span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-input v-model="form.address" placeholder="请输入实际居住地址" />
          </el-col>
        </el-row>

        <!-- <el-row :gutter="15">
          <el-col :span="24">
            <el-form-item label="预约检查项" prop="appointmentitems">
              <el-select v-model="form.appointmentitems" multiple clearable placeholder="请选择预约检查项目"
                style="width: 100%;">
                <el-option v-for="item in checkList" :value="item.itemid" :key="item.itemid" :label="item.name">{{ item.name }}</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row> -->

        <!-- <el-row :gutter="15">
          <el-col :span="12">
            <el-form-item label="预约时间" prop="appointmenttime">
              <el-date-picker clearable v-model="form.appointmenttime" type="datetime" 
                format="YYYY-MM-DD HH:mm"
                value-format="YYYY-MM-DD HH:mm"
                placeholder="请选择预约时间" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" type="textarea" rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Patient">
import { listPatient, getPatient, delPatient, addPatient, updatePatient } from "@/api/system/patient"
import { getAreaTree } from "@/api/system/area" 
import { listCheckitems } from "@/api/system/checkitems"
import dayjs from 'dayjs';
import { onMounted } from "vue";
// import CalendarCell from './CalendarCell.vue'

const { proxy } = getCurrentInstance()

//性别字典
const { sys_user_sex } = proxy.useDict('sys_user_sex')
const { ha_wed_status } = proxy.useDict('ha_wed_status') //婚姻状态
// console.log(sys_user_sex)

const patientList = ref([])
const open = ref(false) //弹出框
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("新增信息")

const indexdate = ref(dayjs().format('YYYY-MM-DD')) 
const options = ref([]) //地区的下拉列表

const checkList = ref([
  // '甲状腺功能测定',
  // '骨代谢功能显像',
  // '心肌灌注显像',
  // '肾动态显像',
  // '肿瘤代谢显像（PET/CT）',
])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    uname: null,
    usex: null,
    ucard: null,
    umobile: null,
    ubirthday: null,
    ssid: null,
    maritalstatus: null,
    addresscity: null,
    address: null,
    appointmenttype: null,
    appointmentitems: null,
    appointmenttime: null,
    sendsms: null,
    ustatus: null,
    pstatus: null,
  },
  rules: {
    uname: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    usex: [{ required: true, message: '请选择性别', trigger: 'change' }],
    ucard: [
      // { required: true, message: '请输入身份证号', trigger: 'blur' },
      {
        pattern: /^[1-9]\d{5}(19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i,
        message: '请输入正确的身份证号',
        trigger: 'blur',
      },
    ],
    umobile: [
      { required: true, message: '手机号不能为空', trigger: 'blur' },
      {
        pattern: /^1[3-9]\d{9}$/,
        message: '请输入正确的手机号',
        trigger: 'blur',
      },
    ],
    // appointmentitems: [{ required: true, message: '请选择预约检查项目', trigger: 'change' }],
    // appointmenttime: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
  }
})

const { queryParams, form, rules } = toRefs(data)

  const newqueryParams = {
    pageNum: 1,
    pageSize: 1000,
  }

// 获取地区树
onMounted(async () => {
  const response = await getAreaTree()
  if (response.code == 200) {
    options.value = response.data
  } else{
    options.value = []
  }
  //查询所有检查项列表
  const checkitemsResponse = await listCheckitems(newqueryParams)
  if (checkitemsResponse.code == 200) {
    checkList.value = checkitemsResponse.rows.map(item => ({
      name: item.itemname,
      itemid: item.itemid,
    })) //名称和itemid形成新数组
    
  } else{
    checkList.value = []
  }
  //

})
const propsNew = ref({
  value: 'name',  // 指定 value 字段为 'code'  //直接用实际地址拼接起来
  label: 'name',  // 指定 label 字段为 'name'
  children: 'children', // 指定子节点字段为 'children'
});

//根据身份证号自动带出出生年月
watch(() => form.value.ucard, extractBirthDate);

function extractBirthDate() {
  const idCard = form.value.ucard;
  if (idCard && idCard.length === 18) {
    const year = idCard.substring(6, 10);
    const month = idCard.substring(10, 12);
    const day = idCard.substring(12, 14);
    form.value.ubirthday = `${year}-${month}-${day}`;
  } else {
    form.value.ubirthday = null;
  }
}


//不可用日期
function disabledDate(time) {
  // time 是候选日期对应的 Date 对象
  return time.getTime() > Date.now()   // 今天 00:00:00 以后全部禁用
}

function handlePanelChange(date) { //面板切换，有效果
  console.log(date)
}



/** 查询患者管理列表 */
function getList() {
  loading.value = true
  listPatient(queryParams.value).then(response => {
    console.log(response.rows)
    // 计算年龄鲍小伟
    response.rows.forEach(item => {
      item.age = proxy.$filters.age(item.ubirthday)
    })
    patientList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    uid: null,
    uname: null,
    usex: '0',
    ucard: null,
    umobile: null,
    ubirthday: null,
    ssid: null,
    maritalstatus: null,
    addresscity: null,
    address: null,
    appointmenttype: null,
    appointmentitems: null,
    appointmenttime: null,
    sendsms: null,
    ustatus: null,
    pstatus: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  }
  proxy.resetForm("patientRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.uid)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "新增信息"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _uid = row.uid || ids.value
  getPatient(_uid).then(response => {
    form.value = response.data
    //处理格式
    form.value.addresscity = JSON.parse(form.value.addresscity)
    // form.value.appointmentitems = JSON.parse(form.value.appointmentitems)
    open.value = true
    title.value = "修改信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["patientRef"].validate(valid => {
    if (valid) {
      if (form.value.uid != null) {
        form.value.addresscity = JSON.stringify(form.value.addresscity)
        form.value.appointmentitems = JSON.stringify(form.value.appointmentitems)
        updatePatient(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        //处理格式
        form.value.addresscity = JSON.stringify(form.value.addresscity)
        form.value.appointmentitems = JSON.stringify(form.value.appointmentitems)
        addPatient(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _uids = row.uid || ids.value
  proxy.$modal.confirm('是否确认删除信息编号为"' + _uids + '"的数据项？').then(function() {
    return delPatient(_uids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/patient/export', {
    ...queryParams.value
  }, `patient_${new Date().getTime()}.xlsx`)
}

getList()
</script>
